package cn.reinforce.util.dsm;

import cn.reinforce.util.dsm.exception.DsmException;
import cn.reinforce.util.dsm.model.ApiInfo;
import cn.reinforce.util.dsm.model.LoginData;
import cn.reinforce.util.dsm.model.Result;
import cn.reinforce.util.http.HttpClientUtil;
import cn.reinforce.util.http.model.HttpResult;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import javax.servlet.http.Cookie;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 幻幻Fate
 * @date 2021/10/19
 */
public class AuthUtil {
    private AuthUtil() {
    }

    public static String login() {
        Dsm dsm = Dsm.INSTANCE;
        HttpResult result = HttpClientUtil.get(dsm.getBaseUrl() + "auth.cgi?api=SYNO.API.Auth&version=" + dsm.getVersion() + "&method=login&account=" + dsm.getUsername() + "&passwd=" + dsm.getPassword() + "&format=cookie");
        Gson gson = new GsonBuilder().create();
        Result<LoginData> res = gson.fromJson(result.getResult(), new TypeToken<Result<LoginData>>() {
        }.getType());
        return res.getData().getSid();
    }

    public static Map<String, ApiInfo> getApiList() {
        Dsm dsm = Dsm.INSTANCE;
        HttpResult result = HttpClientUtil.get(dsm.getBaseUrl() + "query.cgi?api=SYNO.API.Info&version=1&method=query&query=all");
        Gson gson = new GsonBuilder().create();
        Result<Map<String, ApiInfo>> res = gson.fromJson(result.getResult(), new TypeToken<Result<Map<String, ApiInfo>>>() {
        }.getType());
        return res.getData();
    }

    public static String requestData(String apiName, String method, String params, String httpMethod) {
        Dsm dsm = Dsm.INSTANCE;
        String apiPath = dsm.getApis().get(apiName).getPath();

        List<Cookie> cookies = new ArrayList<>();
        cookies.add(new Cookie("id", dsm.getSid()));

        HttpResult result = HttpClientUtil.get(dsm.getBaseUrl() + apiPath + "?api=" + apiName + "&version=" + dsm.getApis().get(apiName).getMaxVersion() + "&method=" + method + params, cookies);
        Gson gson = new GsonBuilder().create();
        Result<Object> res = gson.fromJson(result.getResult(), new TypeToken<Result<Object>>() {
        }.getType());
        if(!res.isSuccess()){
            throw new DsmException(String.valueOf(res.getCode()));
        }
        return gson.toJson(res.getData());
    }
}
